package com.cup.bddm.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cup.bddm.api.controller.BaseController;
import com.cup.bddm.util.WebUtil;

/**
 * 全局拦截器
 */
@Component
public class GlobalHandler extends BaseController implements HandlerInterceptor {
	static Logger logger = Logger.getLogger(GlobalHandler.class);

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object obj) throws Exception {
		req.setAttribute(REQ_TIME, System.currentTimeMillis());
		HandlerMethod handlerMethod = (HandlerMethod) obj;
		if (handlerMethod.getBeanType().isAnnotationPresent(Token.class) || handlerMethod.getMethod().isAnnotationPresent(Token.class)) {
			String stat = tokenStatus();
			if ("".equals(stat)) {
				return true;
			} else {
				writeRes(req, res, stat);
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse res, Object obj, ModelAndView mv) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object obj, Exception e) throws Exception {
		long req_time = (long) req.getAttribute(REQ_TIME);
		String req_ip = WebUtil.getIpAddr(req);
		String req_path = req.getRequestURI();
		String req_body = (String) req.getAttribute(REQ_BODY);
		String res_body = (String) req.getAttribute(RES_BODY);
		StringBuilder sb = new StringBuilder();
		sb.append("Client: ").append(req_ip).append(" ").append(WebUtil.getUserAgent(req)).append(" ").append(req.getContentType());
		logger.info(sb.toString());
		sb.delete(0, sb.length());
		sb.append("Requst: ").append(req.getMethod()).append(" ").append(req_path).append(req.getQueryString() == null ? "" : "?" + req.getQueryString());
		logger.info(sb.toString());
		sb.delete(0, sb.length());
		logger.info("Params: " + req_body);
		logger.info("Respon: " + res_body);
		sb.append("Timeto: ").append(System.currentTimeMillis() - req_time).append("ms");
		logger.info(sb.toString());
	}
}
